package com.coursehub.progress.config;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;

/**
 * JWT认证过滤器
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        log.debug("Processing request: {} {}", request.getMethod(), request.getRequestURI());
        
        String authHeader = request.getHeader("Authorization");
        log.debug("Authorization header: {}", authHeader != null ? "Bearer ***" : "null");
        
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            
            // 从网关传递的用户信息
            String userId = request.getHeader("X-User-Id");
            String userAccount = request.getHeader("X-User-Account");
            
            log.debug("X-User-Id: {}, X-User-Account: {}", userId, userAccount);
            
            if (userId != null && userAccount != null) {
                // 创建认证对象
                UsernamePasswordAuthenticationToken authentication = 
                    new UsernamePasswordAuthenticationToken(userAccount, null, new ArrayList<>());
                
                // 设置用户ID到认证详情中
                authentication.setDetails(userId);
                
                // 设置到安全上下文
                SecurityContextHolder.getContext().setAuthentication(authentication);
                
                log.debug("Authentication set for user: {} (ID: {})", userAccount, userId);
            } else {
                log.warn("Missing user headers - X-User-Id: {}, X-User-Account: {}", userId, userAccount);
            }
        } else {
            log.debug("No valid Authorization header found");
        }
        
        filterChain.doFilter(request, response);
    }
}